package com.qnvip.sbd.util;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.regex.Pattern;

public class IPUtil implements Serializable {
	private static final long serialVersionUID = 2592303288973483612L;

	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip != null && ip.length() > 0){
			String[] ips = ip.split(",");
			for(int i=0;i<ips.length;i++){
				if(ips[i].trim().length() > 0 && !"unknown".equalsIgnoreCase(ips[i].trim())){
					ip = ips[i].trim();
					break;
				}
			}
		}
		return formatIp(ip);
	}
	
	public static String formatIp(String ip){
	String iptem[]=ip.split("\\.");
	String ipstr ="";
	for(int m=0;m<iptem.length;m++){
		if(iptem[m].length()==1){
			iptem[m] = "00"+iptem[m];
		}else if(iptem[m].length()==2){
			iptem[m] = "0"+iptem[m];
		}
		ipstr = ipstr+iptem[m];
	}
	return ipstr;
	}
	
	public static String getIpAddressWithDot(HttpServletRequest request){
		String ip = request.getHeader("x-forwarded-for");   
	      if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	         ip = request.getHeader("Proxy-Client-IP");   
	     }   
	      if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	         ip = request.getHeader("WL-Proxy-Client-IP");   
	      }   
	     if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
	          ip = request.getRemoteAddr();   
	     }   
	     return ip;   
	}
	
	public static String getRealIpAddr(String ipStr){
		if(ipStr == null || ipStr.length() != 12)
			return "�Ƿ�IP";
		String[] ipArray = {ipStr.substring(0, 3), ipStr.substring(3, 6),ipStr.substring(6, 9), ipStr.substring(9, 12)};
		StringBuffer ip = new StringBuffer();
		int i = 0;
		for(String str : ipArray){
			if(str.charAt(1) == '0'){
				if(str.charAt(0) == '0')
					ip.append(str.subSequence(2,3));
				else
					ip.append(str);
			}else if(str.charAt(0) == '0'){
				ip.append(str.subSequence(1,3));
			}else{
				ip.append(str);
			}
			if(i++ < 3 )
				ip.append(".");
		}
		return ip.toString();
	}
	
	/**
	 * @param ip
	 * @return
	 */
	 public static boolean isValidIPAddress(String ip) {
		 String reg = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
		 Pattern patt = Pattern.compile(reg);
		 return patt.matcher(ip).matches();
	}
}
